package de.gzork.server;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.w3c.dom.Document;

import com.google.code.facebookapi.FacebookException;
import com.google.code.facebookapi.FacebookWebappHelper;
import com.google.code.facebookapi.FacebookXmlRestClient;
import com.google.code.facebookapi.IFacebookRestClient;

/**
 * The Facebook User Filter ensures that a Facebook client that pertains to the
 * logged in user is available in the session object named
 * "facebook.user.client".
 * 
 * The session ID is stored as "facebook.user.session". It's important to get
 * the session ID only when the application actually needs it. The user has to
 * authorise to give the application a session key.
 * 
 * @author Dave
 */
public class FacebookUserFilter implements Filter {

	private String api_key = "4153a065027a515064a75ccbd317e7f1";
	private String secret = "1ec80a3ec5b3b40cb014b9db186130d1";

	private static final String FACEBOOK_USER_CLIENT = "facebook.user.client";

	public void destroy() {
	}

	public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException,
			ServletException {
		try {

			HttpServletRequest request = (HttpServletRequest) req;
			HttpServletResponse response = (HttpServletResponse) res;

			HttpSession session = request.getSession(true);
			IFacebookRestClient<Document> userClient = getUserClient(session);
			if (userClient == null) {
				System.out
						.println("User session doesn't have a Facebook API client setup yet. Creating one and storing it in the user's session.");
				userClient = new FacebookXmlRestClient(api_key, secret);
				session.setAttribute(FACEBOOK_USER_CLIENT, userClient);
			}

			System.out
					.println("Creating a FacebookWebappHelper, which copies fb_ request param data into the userClient");
			FacebookWebappHelper<Document> facebook = new FacebookWebappHelper<Document>(request, response, api_key,
					secret, userClient);
			String nextPage = request.getRequestURI();
			nextPage = nextPage.substring(nextPage.indexOf("/", 1) + 1); // cut
																			// out
																			// the
																			// first
																			// /,
																			// the
																			// context
																			// path
																			// and
																			// the
																			// 2nd
																			// /
			System.out.println(nextPage);
			if(!facebook.isLogin()) {
				response.sendRedirect("http://www.facebook.com/login.php?v=1.0&api_key=4153a065027a515064a75ccbd317e7f1&next=gzork&canvas=true");
				return;
			}
			/**
			<script type="text/javascript">
			top.location.href = "http://www.facebook.com/login.php?v=1.0&api_key=4153a065027a515064a75ccbd317e7f1&next=gzork";
			</script><script type="text/javascript">
			top.location.href = "http://www.facebook.com/login.php?v=1.0&api_key=4153a065027a515064a75ccbd317e7f1&next=gzork&canvas=true";
			</script>
			**/
			boolean redirectOccurred ;
//			boolean redirectOccurred = facebook.requireLogin(nextPage);
//			if (!redirectOccurred) {
//				return;
//			}

			boolean fullClient = false;
			for (Cookie cookie : request.getCookies()) {
				if (cookie.getName().contains("session_key")) {
					userClient = new FacebookXmlRestClient(api_key, secret, cookie.getValue());
					session.setAttribute(FACEBOOK_USER_CLIENT, userClient);
					fullClient = true;
					break;
				}
			}

			if (!fullClient) {
				redirectOccurred = facebook.requireFrame(nextPage);
				if (redirectOccurred) {
					return;
				}
			}

			long facebookUserID;
			try {
				facebookUserID = userClient.users_getLoggedInUser();
				System.out.println("facebookUserID = " + facebookUserID);
			} catch (FacebookException ex) {
				response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
						"Error while fetching user's facebook ID");
				System.out.println("Error while getting cached (supplied by request params) value "
						+ "of the user's facebook ID or while fetching it from the Facebook service "
						+ "if the cached value was not present for some reason. Cached value = {}"
						+ userClient.getCacheUserId());
				return;
			}

			// MDC.put(facebookUserId, String.valueOf(facebookUserID));
			
			chain.doFilter(request, response);
		} finally {
			// MDC.remove(ipAddress);
			// MDC.remove(facebookUserId);
		}
	}

	public static FacebookXmlRestClient getUserClient(HttpSession session) {
		return (FacebookXmlRestClient) session.getAttribute(FACEBOOK_USER_CLIENT);
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
		System.out.println("api-key: " + api_key);
	}
}